package com.tech.distribute_lock.redis;

import com.tech.distribute_lock.DistributeLockStategy;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@Slf4j
@Component
public class RedissonDistributeLockStategy implements DistributeLockStategy {

    @Resource
    private Redisson redisson;

    private static final ConcurrentHashMap<String, RLock> lockMap = new ConcurrentHashMap<>();

    /**
     * 尝试获取分布式锁
     * @param lockKey 锁
     * @param expireTime 超期时间，ms
     * @return 是否获取成功
     */
    @Override
    public boolean tryLock(String lockKey, int expireTime) {
        RLock lock = redisson.getLock(lockKey);
        boolean flag = false;
        try {
            flag = lock.tryLock(expireTime, expireTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error("tryLock error ", e);
        }
        if(flag){
            lockMap.put(lockKey, lock);
        }
        return flag;

    }

    @Override
    public void lockWait(int millis){
        LockSupport.parkNanos(millis*1000*1000);
    }

    /**
     * 释放分布式锁
     * @param lockKey 锁
     * @return 是否释放成功
     */
    @Override
    public boolean unLock(String lockKey) {
        RLock rLock = lockMap.get(lockKey);
        boolean flag = false;
        if(rLock.isHeldByCurrentThread()){
            rLock.unlock();
            flag = true;
        }
        return flag;

    }
}
